import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:非递归版本的归并排序
 * User: Admin
 * Date: 2022-06-02
 * Time: 18:55
 */
public class TestDemo {
    public static void merge(int[] array,int left, int right,int mid) {
        int e1 = left;
        int e2 = mid;
        int a1 = mid+1;
        int a2 = right;

        int[] tmpArr = new int[right-left+1];
        int k = 0;
        while(e1 <= e2 && a1 <= a2) {

            if(array[e1] <= array[a1]) {
                tmpArr[k++] = array[e1++];
            } else {
                tmpArr[k++] = array[a1++];
            }
        }

        while(e1 <= e2) {
            tmpArr[k++] = array[e1++];
        }

        while(a1 <= a2) {
            tmpArr[k++] = array[a1++];
        }

        for (int i = 0; i < k; i++) {
            array[i+left] = tmpArr[i];
        }
    }

    public static void mergeSort(int[] array,int left,int right) {
        int gap = 1;

        while(gap < array.length) {
            for (int i = 0; i < array.length; i+=gap*2) {
                left = i;
                int mid = left+gap-1;
                if(mid >= array.length) {
                    mid = array.length-1;
                }
                right = mid+gap;
                if(right >= array.length) {
                    right = array.length-1;
                }
                merge(array,left,right,mid);
            }
            gap *=2;
        }

    }

    public static void main(String[] args) {
        int[] array= {5,6,7,1,2,3,5,8,10};
        mergeSort(array,0,array.length-1);
        System.out.println(Arrays.toString(array));
    }
}
